package server

import (
	"discoveries-rpc/model"
	"discoveries-rpc/proto/articles_srv"
)

func articlesPbToModel(in *articles_srv.ArticlesInfos) *model.Articles {
	return &model.Articles{
		Model:       model.Model{ID: in.Id},
		Title:       in.Title,
		Content:     in.Content,
		ArticlesImg: in.ArticlesImg,
		Author:      in.Author,
	}
}

func articlesModelToPb(in *model.Articles) *articles_srv.ArticlesInfo {
	return &articles_srv.ArticlesInfo{
		Id:          in.ID,
		Title:       in.Title,
		Content:     in.Content,
		ArticlesImg: in.ArticlesImg,
		Author:      in.Author,
		LikeCount:   in.LikeCount,
		ReadCount:   in.ReadCount,
	}
}

// 发现文章创建
func ArticlesCreate(in *articles_srv.ArticlesInfos) (*articles_srv.ArticlesInfo, error) {
	toModel := articlesPbToModel(in)
	create, err := toModel.ArticlesCreate()
	return articlesModelToPb(create), err
}

// 发现文章详情
func ArticlesShow(id int64) (*articles_srv.ArticlesInfo, error) {
	m := new(model.Articles)
	show, err := m.ArticlesShow(id)
	return articlesModelToPb(show), err
}

// 发现文章修改
func ArticlesUpdate(in *articles_srv.ArticlesInfos) (*articles_srv.ArticlesInfo, error) {
	update, err := articlesPbToModel(in).ArticlesUpdate(in.Id)
	return articlesModelToPb(update), err
}

// 发现文章删除
func ArticlesDelete(id int64) (*articles_srv.ArticlesInfo, error) {
	m := new(model.Articles)
	articlesDelete, err := m.ArticlesDelete(id)
	return articlesModelToPb(articlesDelete), err
}

// 发现文章列表
func ArticlesList(title string) ([]*articles_srv.ArticlesInfo, error) {
	m := new(model.Articles)
	list, err := m.ArticlesList(title)
	if err != nil {
		return nil, err
	}
	var articlesList []*articles_srv.ArticlesInfo
	for _, v := range list {
		articlesList = append(articlesList, articlesModelToPb(v))
	}
	return articlesList, err
}

func LikeCountPbToModel(id int64) *model.Articles {
	return &model.Articles{
		Model: model.Model{ID: id},
	}
}

// 增加收藏
func LikeCountRise(id int64) (*articles_srv.ArticlesInfo, error) {
	_, err := LikeCountPbToModel(id).LikeCountRise(id)
	show, err := LikeCountPbToModel(id).ArticlesShow(id)
	return articlesModelToPb(show), err
}

// 减少收藏
func LikeCountMinimize(id int64) (*articles_srv.ArticlesInfo, error) {
	_, err := LikeCountPbToModel(id).LikeCountMinimize(id)
	show, err := LikeCountPbToModel(id).ArticlesShow(id)
	return articlesModelToPb(show), err
}

func ReadCountRisePbToModel(id int64) *model.Articles {
	return &model.Articles{
		Model: model.Model{ID: id},
	}
}

// 增加阅读数
func ReadCountRise(id int64) (*articles_srv.ArticlesInfo, error) {
	_, err := ReadCountRisePbToModel(id).ReadCountRise(id)
	show, err := ReadCountRisePbToModel(id).ArticlesShow(id)
	return articlesModelToPb(show), err
}
